<template>

    <div class="translation" curPageName="clearsfsa342s555542342">
       <!-- //清关 -->
    
        <div class="merak-container-has-search" v-waterMarker v-loading="pageLoading">
    
            <div class="container merak-card">
                <div class="header" >
                    <div class="title"  @click.stop="one_collapse=!one_collapse">  
                        <CaretTop v-if="one_collapse" style="width: 1em; height: 1em; margin-right: 8px" />
                        <CaretBottom v-else style="width: 1em; height: 1em; margin-right: 8px" />
                        
                        {{$t("goods_attribute.property_clearance")}}
                        
                    </div>
                    <div class="btns">
                        <div v-if="one_edit">
                            <el-button @click="stats_info_cancel()">{{ $t("merak.cancel") }}</el-button>
                            <el-button @click=submitFormOne(formoneRef) type="primary">{{ $t("merak.save") }}</el-button>
                        </div>
                        <el-button v-else type="primary" :icon="Edit" @click="stats_info_edit()" link style="padding: 0; min-width: auto;">
                            {{ $t("merak.edit") }}
                        </el-button>
                    </div>
                </div>
                <div class="body" v-if="one_collapse">



                    
                   
                    <el-form v-if="one_edit" ref="formoneRef" labelPosition="top" :model="info_arr" :rules="formoneRules">
						<el-row :gutter="40">
							<el-col :span="6">
								<el-form-item :label='$t("goods_attribute.type_id")'>
                                    <el-input class="qf_input" type="text" v-model="info_arr.type_id_txt" disabled/>
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-form-item :label='$t("goods_attribute.cc_property_en")'>
									<el-input class="qf_input" type="text" v-model="info_arr.cc_property_en" disabled/>
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-form-item :label='$t("goods_attribute.cc_property")' prop="cc_property"  :error="newRules.cc_property">
									<el-input maxlength="100"  class="qf_input" type="text" v-model="info_arr.cc_property"/>
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-form-item :label='$t("goods_attribute.cc_property_cn")' prop="cc_property_cn" :error="newRules.cc_property_cn">
									<el-input maxlength="50"  class="qf_input" type="text" v-model="info_arr.cc_property_cn"/>
								</el-form-item>
							</el-col>
                            
							<el-col :span="6">
								<el-form-item :label='$t("goods_attribute.sort")'  prop="sort">
                                    <el-input  maxlength="5" class="qf_input" type="text" v-num v-model="info_arr.sort"/>
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-form-item :label='$t("goods_attribute.cc_prop_type")' prop="cc_prop_type">
									<el-select @change="select_text_change(info_arr.cc_prop_type,dataarr.cc_prop_type,'cc_prop_type_txt')" class="qf_select" :placeholder="$t('merak.placeholder_select')" v-model="info_arr.cc_prop_type">
										<el-option
										  :label="item.label"
										  :value="item.value"
										  v-for="item in dataarr.cc_prop_type"
										  :key="item"
										/>
									</el-select>
								</el-form-item>
							</el-col>
							
							<el-col :span="6">
								<el-form-item :label='$t("goods_attribute.cc_is_required")' prop="cc_is_required">
									<el-radio-group v-model="info_arr.cc_is_required">
										<el-radio :value="0">{{$t("merak.no")}}</el-radio>
										<el-radio :value="1">{{$t("merak.yes")}}</el-radio>
									</el-radio-group>
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-form-item :label='$t("goods_attribute.for_sku")'  prop="is_spec" v-if="routerType=='food' || routerType=='consumer'">
									<el-radio-group  v-model="info_arr.is_spec">
                                        <el-radio :value="0">{{$t("merak.no")}}</el-radio>
										<el-radio :value="1">{{$t("merak.yes")}}</el-radio>
									</el-radio-group>
								</el-form-item>
							</el-col>
							
						</el-row>
				</el-form>

                    


                    <el-form v-else  labelWidth="auto"  labelPosition="right" >
                        <el-row :gutter="40">
                            <el-col :span="6">
                                <el-form-item :label='$t("goods_attribute.type_id")'>
                                        {{info_arr.type_id_txt}}
                                 </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item  :label='$t("goods_attribute.cc_property_en")' >
                                    {{info_arr.cc_property_en}}
                                 </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item :label='$t("goods_attribute.cc_property")' >
                                    {{info_arr.cc_property}}
                                 </el-form-item>
                            </el-col>
                           
                            <el-col :span="6">
                                <el-form-item  :label='$t("goods_attribute.cc_property_cn")' >
                                    {{info_arr.cc_property_cn}}
                                 </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item :label='$t("goods_attribute.sort")' >
                                    {{info_arr.sort}}
                                 </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item :label='$t("goods_attribute.cc_prop_type")'>
                                    {{info_arr.cc_prop_type_txt}}
                                 </el-form-item>
                            </el-col>
                          
                            <el-col :span="6">
                                <el-form-item :label='$t("goods_attribute.cc_is_required")' >
                                        {{info_arr.cc_is_required==1?$t("merak.yes"):$t("merak.no")}}
                                 </el-form-item>
                            </el-col>
                            <el-col :span="6">
                            
                                <el-form-item :label='$t("goods_attribute.for_sku")' v-if="routerType=='food' || routerType=='consumer'">
                                    {{info_arr.is_spec==1?$t("merak.yes"):$t("merak.no")}}
                                 </el-form-item>
                            </el-col>
                           
                          
                        </el-row>
                    </el-form> 



                  


                </div>

            </div>




            <!-- v-if="info_arr.cc_prop_type=='dropdown'" -->

            <!--  -->
            <div class="container merak-card" style="margin:10px 0"  v-if="info_arr.cc_prop_type=='dropdown'">


                <div class="header" >
                    <div class="title"  @click.stop="two_collapse=!two_collapse">  
                        <CaretTop v-if="two_collapse" style="width: 1em; height: 1em; margin-right: 8px" />
                        <CaretBottom v-else style="width: 1em; height: 1em; margin-right: 8px" />
                        
                        {{$t("goods_attribute.attribute_value_list")}}
                        <div class="msgVal" style="">（{{$t("goods_attribute.all_key")}}<span>{{state.data.length}}</span>{{$t("goods_attribute.linenum")}}）</div>
                  
                    
                    </div>
                    <div class="btns">
                        <div v-if="two_edit">
                           
                            <el-button @click="two_edit=false">{{ $t("merak.cancel") }}</el-button>
                            <el-button type="primary" plain @click="addRows">{{$t("goods_attribute.add_enumeration_value")}}</el-button>
                            <!-- 只有枚举类型是单选 -->
                            <el-button v-if="info_arr.cc_prop_type=='dropdown'" type="primary" plain @click="propTemplateFile">{{$t('goods_attribute.export_templete')}}</el-button>
                            <el-button @click=submitFormTwo() type="primary">{{ $t("merak.save") }}</el-button>
                        </div>
                        <el-button v-else type="primary" :icon="Edit" @click="stats_table_edit()" link style="padding: 0; min-width: auto;">
                            {{ $t("merak.edit") }}
                        </el-button>
                    </div>
                </div>

                <div class="body" v-show="two_collapse">

                    <div  v-show="two_edit" style="height: 600px;display: flex; flex-direction: column;">
                            <basicTableSum ref="editTableRef" v-bind="tableConfig" @editFormFun="editFormClick">
                            
                                <template #handle="{ row }">
                    
                                    <el-button v-if="row.del.value==1" type="danger" link @click="delFun(row)">{{$t("merak.delete")}}</el-button>
                                    <el-button v-else type="danger" disabled link >{{$t("merak.delete")}}</el-button>
                              
                                </template>
                            </basicTableSum>
                        </div>
        
                    <div v-show="two_edit==false">
                        <!-- <serachBar custom_class="myclass" :close-plan="true" :close-advanced="true"
                            :placeholder='$t("goods_attribute.prop_key_seach")' :search_val=search_val @search-event="searchFn">
                          
                        </serachBar> -->
                        <div class="merak-table-wrapper"  style="height: 600px;margin-top:20px">
                        
                    <MerakXTable :columns-by-store="JSON.parse(JSON.stringify(state.columns))" 
                    :columns="state.columns"
                  
                    :toolbar="[{ type: 'reload', title: '刷新'}]"
                    ref="MerakXTableRef"
                    @tool-click="handleToolClick"
                        :data="state.data" :enabled-tree="true" :pagination="false"  :enabled-scroll="false"
                        align="left" header-align="left" :tree-expand-all="true">

                        <template #tools>

                            <el-input
                            v-model="search_val"
                            size="small"
                            :placeholder='$t("goods_attribute.prop_key_seach")'
                            style="width: 200px"
                            :suffix-icon="Search"
                            clearable
                            @change="getdetaidataFun()"
                            />

                       
                           
                                

                        </template>


                        






                        
                    </MerakXTable>








                        
                    </div>

                    </div>
                




                    
                            


                        </div>

                    </div>
























                
                </div>


        <div>
      <clearPropTemplate    :dialogQifaProp="dialogQifaProp" :typeId="info_arr.type"  :propId="info_arr.cc_prop_id"  @drawerCloseDialog="drawerCloseDialog"></clearPropTemplate>
    </div>

    </div>























</template>

<script lang="ts" setup name="manageSet">
import { Plus, Edit, Delete, EditPen ,CaretTop,CaretBottom} from '@element-plus/icons-vue';

import { ref, reactive, onMounted, getCurrentInstance } from "vue";
import serachBar from "@/components/SearchBar/index";
import { 
  Search, 
} from '@element-plus/icons-vue'
import MerakXTable, { MerakXTableInstance, MerakXTableColumn, MerakXTableQuery } from "@/components/MerakXTable";
import { moreConfirm, confirmWarningMsg, successMsg, warnMsg, failMsg, confirmSuccessMsg, delConfimMsg } from "@/utils/messageUtils";
import I18n from "@/languages/index";
import basicTableSum from "@/components/MerakEditTable/components/basicTable/moreEdit.vue"
import { editClearancGoodsProperty,saveClearancOne,saveClearancTwo} from "@/api/modules/goodsArchive/allocation";
import type { ElForm } from "element-plus";
import { useRouter, useRoute } from 'vue-router';
import clearPropTemplate from "./clearPropTemplate.vue";
const router = useRouter();
const route = useRoute();




type FormInstance = InstanceType<typeof ElForm>;
const setRef = ref<FormInstance>();
const pageLoading=ref(true);

const { proxy } = getCurrentInstance();


const tableRef = ref<MerakXTableInstance>();

const MerakXTableRef=ref();

const routerType = router.currentRoute.value.query.type;
const routerPropId = router.currentRoute.value.query.prop_id;
console.log(routerType,routerPropId)

const change_id_arr=ref([]);
const newRules = reactive({});



const resetForm = (formEl: FormInstance | undefined) => {
	  if (!formEl) return
	  formEl.resetFields()
	}



const handleToolClick: MerakXTableInstance["onTool-click"] = type => {
  console.log(type);
  if(type=='reload'){
    getdetaidataFun()
  }
};

const select_text_change = (value,options,txtvalue) => {
    const selectedLabel=options.filter(
                    (item: Record<string, any>) =>{
                        if(item.value==value){
                           return item.label
                        }
                    }   
                    )
    const info_arr_new=JSON.parse(JSON.stringify(info_arr.value));
    info_arr_new[txtvalue]=selectedLabel[0].label;
    info_arr.value=info_arr_new;
   

}




//批量操作
const handleBatchClick = async (e) => {
    console.log(e)

   

}


//#region 搜索表单
let search_val = ref("");
//触发了快速搜索或者搜索方案
const searchFn = params => {
    console.log(params)
    
    var severice_data=JSON.parse(JSON.stringify(init_list_data.value));
    var newdata=[];
    for (let index = 0; index < severice_data.length; index++) {
        const element = severice_data[index];
        if(element.cc_propvalue.indexOf(params.search)>-1 || element.cc_propvalue_cn.indexOf(params.search)>-1){
            newdata.push(element)
        }
        
    }

    state.data=newdata;


    
};

//#endregion


//权限01数据
let authArr = ref({});

const $t = I18n.global.t;
	const state = reactive<{
		columns : MerakXTableColumn[];
		data : any;
	}>({
		columns: [
		    {    field: "cc_propvalue_id", title: "属性值ID" ,width:"140px"},
			{ field: "cc_propvalue", title: "属性值(俄文)",length:'100'},
			{ field: "cc_propvalue_cn", title: "属性值(中文)",length:'50' },
			{ field: "remark", title: "属性描述(俄文)" },
			{ field: "remark_cn", title: "属性描述(中文)" },
		],
      
        
		data: [
          

		]
	});


    const init_list_data=ref([
           


		])

  
    onMounted(async () => {
        getdetaidataFun()
    })
   



    const dataarr=ref({});


const getdetaidataFun=()=> {
    console.log(routerType,routerPropId)
    
    editClearancGoodsProperty(routerType,{"prop_id":routerPropId}).then(res => {
        pageLoading.value=false;
			if (res.code == ResultEnum.SUCCESS) {
                console.log(search_val.value)
           
                state.data=res.data.defaults.propvalueList.filter(
                    (item: Record<string, any>) =>
                        item.cc_propvalue.includes(search_val.value) || item.cc_propvalue_cn.includes(search_val.value)
                    )






                init_list_data.value=res.data.defaults.propvalueList;
                info_arr.value=res.data.defaults;

                dataarr.value=res.data.dataarr;
			}else{
                failMsg(res.message);
            }
		})
}








// 属性编辑页面代码

const info_arr=ref(
    {
       "type_id":"",//商品类型
       "cc_property":"",//属性名称(俄文)
       "cc_property_cn":"",//属性名称(中文)
       "cc_property_en":"",//属性名称(英文)
       "cc_prop_type":"dropdown",//属性类型
       "cc_is_required":"1",//是否必填
       "is_spec":"0",//是否是规格
       "sort":"",//排序
   }
)
const validateInput = (rule, value, callback) => {
	  const regexPattern = /^[a-z][a-z0-9_]*$/; //这里是一个简单的正则表达式，匹配字母和数字
	  if (!value || !regexPattern.test(value)) {
	    return callback(new Error(proxy!.$t("goods_attribute.input_error")));
	  }
	  callback();
	};

const formoneRef = ref < FormInstance > ();
const formoneRules=reactive({
        
    type_id: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "change" }],
    cc_property: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "change" }],
    cc_property_cn: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "change" }],
    property_en: [
			{
				validator: validateInput, 
				trigger: 'blur' ,
			},
			{
				required: true,
				message: proxy!.$t("goods_attribute.require"),
				trigger: 'blur',
			},
		],

    cc_prop_type: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "change" }],
    cc_is_required: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "change" }],
    is_spec: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "change" }],
    sort: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "change" }],

       
    });



//编辑第一块内容
const one_edit=ref(false);
const one_collapse=ref(true);
const info_arr_copy=ref()

const stats_info_edit=()=>{
    one_edit.value=true;
    info_arr_copy.value=JSON.parse(JSON.stringify(info_arr.value));
    one_collapse.value=true;
    if(Object.keys(newRules).length > 0){
                    Object.keys(newRules).map((key) => {
                        newRules[key] = undefined;
                    }); 
                }
    
}
const stats_info_cancel=()=>{
    one_edit.value=false;
    info_arr.value=info_arr_copy.value;
}

const submitFormOne = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            var postdata={
                id:routerPropId,
                "prop":info_arr.value
            }
            saveClearancOne(routerType,postdata).then(res => {
			if (res.code == ResultEnum.SUCCESS) {
                successMsg('保存成功!');
                one_edit.value=false;

               

              
			}else{

                if(Object.keys(newRules).length > 0){
                    Object.keys(newRules).map((key) => {
                        newRules[key] = undefined;
                    }); 
                }
                Object.assign(newRules,res.errors);
                if(newRules.length<1){
                    failMsg(res.message);
                }
             
            
            }
		})
          
            console.log("submit!");
        } else {
            console.log("error submit!", fields);
        }
    });
};












const two_edit=ref(false);
const two_collapse=ref(true);
const  tableHeadData=[
              

            ]

            
 const  headConfig={
         
                cc_propvalue:{type:"input"},
                cc_propvalue_cn:{type:"input"},
                remark:{type:"input"},
                remark_cn:{type:"input"},
             
               
            }
 const  tableData=[
 

    ]

    
const tableConfig = reactive({
                headData: tableHeadData,//表格头部数据   必须值
                tableData: tableData,//表格内容数据      必须值
                headConfig: headConfig,//可编辑列类型    必须值 
    
           
              
           })
         
const stats_table_edit=()=>{
    two_edit.value=true;
    tableConfig.headData=state.columns;






    change_id_arr.value=[];
    
    var severice_data=JSON.parse(JSON.stringify(state.data));
    var edittable_data=[];
    for (let index = 0; index < severice_data.length; index++) {
        const element = severice_data[index];
        var obj_f={};
        for (var i in element){
            var _obj={};
              _obj["label"]=element[i];
              _obj["value"]=element[i];
              obj_f[i]=_obj;
        }
        edittable_data.push(obj_f)
        
    }
    tableConfig.tableData=edittable_data;
    two_collapse.value=true;
}

const editTableRef=ref();
const submitFormTwo=()=> {
    var propListPage= editTableRef.value.submitData();
    console.log(propListPage)

    var severice_data=JSON.parse(JSON.stringify(state.data))


    var edit_table_id_arr=[]
    var new_cc_propvalue=[];
    var new_cc_propvalue_cn=[];
    var go=1;
    for (let index = 0; index < propListPage.length; index++) {
        const element = propListPage[index];
        
        edit_table_id_arr.push(element.cc_propvalue_id)


       // 判断属性值不能重复 cc_propvalu
        if(element.cc_propvalue==''){
            tableConfig.tableData[index].cc_propvalue.errTip ='属性值不能为空';  
            go=0;
        }
        if(element.cc_propvalue_cn==''){
            tableConfig.tableData[index].cc_propvalue_cn.errTip ='属性值不能为空';  
            go=0;
        }


        var cur_cc_propvalue = element.cc_propvalue.split(/[\t\r\f\n\s]*/g).join('');
        if(new_cc_propvalue.includes(cur_cc_propvalue)){
            tableConfig.tableData[index].cc_propvalue.errTip ='属性值不能重复';  
            go=0;
        }else{
            new_cc_propvalue.push(cur_cc_propvalue)
        }

        var cur_cc_propvalue_cn = element.cc_propvalue_cn.split(/[\t\r\f\n\s]*/g).join('');
        console.log(cur_cc_propvalue_cn)
        console.log(new_cc_propvalue_cn)
        if(new_cc_propvalue_cn.includes(cur_cc_propvalue_cn)){
           
            tableConfig.tableData[index].cc_propvalue_cn.errTip ='属性值不能重复';  
            go=0;
        }else{
            new_cc_propvalue_cn.push(cur_cc_propvalue_cn)
        }














        // if(element.cc_propvalue=='' || element.cc_propvalue_cn=='' ){
        //     failMsg('属性值中文或者属性值俄语不能为空');
        //     console.log("ssdfsdafasdf")
        //     return false;
        // }


 
       
  
       



       




       
        
    }


    console.log(go)
    if(go==0){
         return false
    }

    var show_table_id_arr=[];
    for (let index = 0; index < severice_data.length; index++) {
        const element = severice_data[index];
        show_table_id_arr.push(element.cc_propvalue_id)
    }

    console.log(show_table_id_arr)
    console.log(edit_table_id_arr)

    var delarr=[]
    for (let i = 0; i < show_table_id_arr.length; i++) {
        if(edit_table_id_arr.includes(show_table_id_arr[i])){
            
        }else{
            if(show_table_id_arr[i]!=0){
                delarr.push(show_table_id_arr[i])
            }
           
        }
        

    }
    console.log(delarr)

    


    var edit_propListPage=JSON.parse(JSON.stringify(propListPage))

var post_prop_list=[]

for (let index = 0; index < edit_propListPage.length; index++) {
    const element = edit_propListPage[index];
    console.log(element.cc_propvalue_id)
    
   if(element.cc_propvalue_id==''  ||  change_id_arr.value.includes(element.cc_propvalue_id)){

    post_prop_list.push(element)
   }else{
    console.log("删除"+element.cc_propvalue_id)
    //edit_propListPage.splice(index, 1);
       
      }
}


console.log(change_id_arr.value)
console.log(post_prop_list)
console.log(delarr)
if(post_prop_list.length<1 && delarr.length<1){
    two_edit.value=false;
    return false;

}
   
    




    var postdata={
                id:routerPropId,
                "propval":post_prop_list,
                "delarr":delarr
            }
            saveClearancTwo(routerType,postdata).then(res => {
                if (res.code == ResultEnum.SUCCESS) {
                successMsg('保存成功!');
                state.data=propListPage;
                two_edit.value=false;
                getdetaidataFun()
                MerakXTableRef.value.reloadData()






              
			}else{
                failMsg(res.message);
            }
        })
}
const delFun = (e) => {
		tableConfig.tableData.splice(e.index, 1);
	}

// 第二块添加属性值
const addRows = () => {
		
		let obj = {
            del:{
                label: "",
				value: 1,

            },
            cc_propvalue_id:{
                label: "-",
				value: "",

            },
			cc_propvalue: {
				label: "",
				value: "",
			},
			cc_propvalue_cn: {
				label: "",
				value: ""
			},
			remark: {
				label: "",
				value: ""
			},
			remark_cn: {
				label: "",
				value: ""
			},
		};
        tableConfig.tableData.push(obj)
		
	}

       
        




    const  editFormClick=(item)=>{
    console.log(item.cc_propvalue_id.value)
    console.log(change_id_arr.value)
    if(change_id_arr.value.includes(item.cc_propvalue_id.value)){

    }else{
        change_id_arr.value.push(item.cc_propvalue_id.value)
    }

}  

         



//#region 模版
  
const dialogQifaProp = ref(false);
const propTemplateFile = () => {
  dialogQifaProp.value = true;

  // console.log(info_arr.value)
};

const drawerCloseDialog = obj => {
  dialogQifaProp.value = false;
  if (obj.type == "refresh") {
    two_edit.value = false;
        getdetaidataFun();
        MerakXTableRef.value.reloadData();
  }
};

//#endregion





</script>

<style lang="scss" scoped>
.el-tag {
    border: none;
    aspect-ratio: 1;
}

.translation {
    height: 100%;


}


.el-color-dropdown__btns .el-button {
    padding: 5px 10px !important;
    min-width: 20px;
}

// :deep(.el-color-dropdown) {
//     .el-button {
//        padding:5px 10px;
//     }
// }





.merak_modal {
    .form-box {

        .el-form-item {}
    }
}








.container {
    display: flex;
    flex-direction: column;
    height: 100%;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
       
        height: var(--merak-button-size);
        font-size: 16px;
        position: relative;
  


        .title{
            width:30%;
            padding:10px 0;
            cursor: pointer;
            user-select:none;
			display: flex;
			align-items: center;
			.msgVal{
				color: #afafaf;
				font-size: 12px;
				span{
					color: var(--el-color-primary);
					font-weight: bold;
					padding: 0 2px;
				}
			}
        }











        .btns{
            position: absolute;
            right: 0;
            top:0;
            z-index:9;
            line-height: 30px;
        }
    }

    .body {
        margin-top:20px;
        flex: auto;
        min-height: 0;

        .el-form.el-form--label-right {
        :deep(.el-form-item__label-wrap) {
          margin-right: 30px;
        }
      }
    }
}

</style>